// ==UserScript==
// @name         js-core
// @namespace    http://tampermonkey.net/
// @version      1.2
// @description  try to take over the world!
// @author       emok
// @match        http://*/*
// @include      https://*/*
// @include      **
// @grant        none
// ==/UserScript==

(function(w) {
    'use strict';

    // Your code here...
    /*
setTimeout(function (){
console.log('log..')
}, 500);
    */
    console.log('load core...')
    var emptyStr = 'nothing...';
    function Clazz(arg) {
        this.arg = arg;
        this.elements=[];
		this.length = 0;
        switch(typeof arg){
            case 'function' :
                this.domReady(arg);
                break;
            case 'string' :
                this.elements = this.selectElem(arg);
				this.length = this.elements.length;
                break;
            case 'object' :
                this.elements.push(arg);
                break;
        }
    };
    //DOM ready onload 如果参数是函数，则进行domReady操作

    Clazz.prototype = {
        log: function(info){
            console.log('log: ',info || emptyStr);
        },
        selectElem: function(arg){
			// console.log('select...',arg || emptyStr);
            var args = arg.split(' ');
			var aChild = [];
			var aParent = [document];
			for(var i = 0;i < args.length;i++){
				aChild = this.selectByStr(aParent, args[i]);
				aParent = aChild
			}
			return aChild;
        },
		selectByStr:function(nodeParaent,arg){
			var aChild=[];
			for(var i=0;i<nodeParaent.length;i++){
				switch(arg.charAt(0)){
					//id选择器  eg: #box  使用document.getElementById选取
					case '#':
						var obj=document.getElementById(arg.substring(1));
						aChild.push(obj);
						break;
					//类选择器  eg: .box  使用上面封装的getByClass选取
					case '.':
						//由于一个标签可以有多个类选择器 所以需要进行循环选取
						var aClassRes = nodeParaent[i].getElementsByClassName(arg.substring(1));
						for(var j=0;j<aClassRes.length;j++){
							aChild.push(aClassRes[j]);
						}
						break;
					default:
						var aTagRes=nodeParaent[i].getElementsByTagName(arg);
						for(var k=0;j<aTagRes.length;k++){
							aChild.push(aTagRes[k]);
						}
						break;
				}
			}
			return aChild;
		},
        trigger: function(eventStr) {
            //  console.log('trigger...',eventStr || emptyStr,this.elements);
			for (var i = 0; i < this.elements.length; i++) {
				this.triggerElem(this.elements[i], eventStr);
			}
        },
		triggerElem: function(elem, eventStr) {
            // console.log('triggerElem...',eventStr || emptyStr);
			if (!elem) {
				return false;
			}
			if (!eventStr) {
				return false;
			}
			return elem.dispatchEvent(new Event(eventStr));

        },
        domReady: function(fn){
			// console.log('domReady... ');
            // FF chrome
            if(document.addEventListener){
                //jquery中已经省略false，false解决低版本火狐兼容性问题
                document.addEventListener('DOMContentLoaded',fn,false);
            }else{
                document.attachEvent('onreadystatechange',function(){
                    if(document.readyState=='complete'){
                        fn();
                    }
                });
            }
        },
        getClassArray: function (elem){
			elem = elem || this.getTopElem();
            var classNames = elem.className;
            if (!classNames) {
                return [];
            }
            return classNames.split(' ');
        },
        hasClass: function (){
			var elem = '';
			var className = '';
			switch (arguments.length) {
				case 1:
					if (this.elements.length == 0) {
						return '';
					}
					elem = this.getTopElem();
					className = arguments[0];
				break;
				case 2:
					elem = arguments[0];
					className = arguments[1];
					if (!elem) {
						return false;
					}
					if (!className) {
						return false;
					}
				break;
			}
			var names = this.getClassArray(elem);
			return names.includes(className);

        },
		getTopElem: function(){
			if (this.elements.length == 0) {
				return document;
			}
			return this.elements[0];
		},
		visibilityChange:function(fn){
			// 不同浏览器 hidden 名称
			var hiddenProperty = 'hidden' in document ? 'hidden' :
				'webkitHidden' in document ? 'webkitHidden' :
				'mozHidden' in document ? 'mozHidden' :
				null;
			// 不同浏览器的事件名
			var visibilityChangeEvent = hiddenProperty.replace(/hidden/i, 'visibilitychange');
			var onVisibilityChange = function(){
				var active = !document[hiddenProperty];
				// if (active) {
				// 	console.log('页面激活');
				// }else{
				// 	console.log('页面非激活');
				// }
				fn(active);
			}
            document.addEventListener(visibilityChangeEvent, onVisibilityChange);
		},
		pageActive: function(fn){
			if (typeof fn != 'function') {
				return;
			}
			this.visibilityChange(function(active){
				if (active) {
					fn();
				}
			});
		},
		addElemStyle: function (elem, styleName, styleValue) {
			elem.style[styleName] = styleValue;
		},
		addStyle: function (styleName, styleValue) {
			for (var i = 0; i < this.elements.length; i++) {
				this.addElemStyle(this.elements[i], styleName, styleValue);
			}
		},
		show: function () {
			this.addStyle('display','')
		},
		hide: function () {
			this.addStyle('display', 'none');
		}
    }
    w._core = function (arg) {
        return new Clazz(arg);
    }

})(window);